package org.xingyun.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisPoolUtils {

    private static Properties properties;

    private JedisPoolUtils() {
    }

    static {
        try {
            InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
            properties = new Properties();
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //返回jedis
    public static Jedis getJedis() {
        //创建连接池的配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        //控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
        //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
        config.setMaxTotal(Integer.parseInt(properties.getProperty("MaxTotal")));
        //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
        config.setMaxIdle(Integer.parseInt(properties.getProperty("MaxIdle")));
        //最少空闲
        config.setMinIdle(Integer.parseInt(properties.getProperty("MinIdle")));

        //连接池
        JedisPool pool = new JedisPool(config, properties.getProperty("host"), Integer.parseInt(properties.getProperty("port")),
                Integer.parseInt(properties.getProperty("timeout")));

        //JedisPool pool = new JedisPool(config, "localhost", 6379, 2000, "123456"); 可以设置密码
        //从连接池获取对象
        Jedis jedis = pool.getResource();

        return jedis;
    }

}
